package impl_v1.server;

import impl_v1.factory.FactoryImpl;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import model.factory.Factory;
import model.server.AuctioningSystem;

public class AuctioningSystemServer {

	private static Registry registry;

	public static final String SERVER_REMOTE_EXCEPTION = "Error : Server disconnected !";
	public static final String NO_SERVERS_AVAILABLE_EXCEPTION = "Error : No more servers available !";

	public static void main(String args[]) {
		createServer();
	}

	public static void createServer() {
		try {
			registry = LocateRegistry.createRegistry(1099);

			Factory factory = new FactoryImpl();
			AuctioningSystem auctioningSystem = factory.getAuctioningSystem();

			Naming.rebind("rmi://localhost/AuctioningSystemService", auctioningSystem);
			System.out.println("Server started");
		} catch (RemoteException e) {
			System.err.println(AuctioningSystemServer.SERVER_REMOTE_EXCEPTION);
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("Server Error: " + e);
		}
	}

	public static void closeServer() {
		try {
			Naming.unbind("rmi://localhost/AuctioningSystemService");
			UnicastRemoteObject.unexportObject(registry, true);
			System.out.println("Server closed");
		} catch (RemoteException | MalformedURLException | NotBoundException e) {
			System.err.println(AuctioningSystemServer.SERVER_REMOTE_EXCEPTION);
		}
	}
}
